package com.open.party.cloud.viewModel;

import cn.android.x.model.data.ResultInfo
import com.open.party.cloud.ServerConfig
import com.open.party.cloud.model.StudyRecordBean
import com.open.party.cloud.model.StudyRecordVo
import com.open.party.cloud.model.TownshipVo
import com.open.party.cloud.model.data.Api
import com.sinothk.rxretrofit.RxRetrofit
import org.greenrobot.eventbus.EventBus
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers


class OrgViewModel {

    fun saveOrUpdateStudyRecord(vo: StudyRecordVo, flag: String) {
        RxRetrofit.init(ServerConfig.SERVER_URL, ServerConfig.getHeader())
            .create(Api::class.java)
            .saveOrUpdateStudyRecord(vo)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Subscriber<ResultInfo<StudyRecordBean>>() {

                override fun onCompleted() {}

                override fun onError(e: Throwable) {
                    val result = ResultInfo<StudyRecordBean>(ResultInfo.ERROR, ResultInfo.getErrorMsg(e.message))
                    result.eventType = "saveOrUpdateStudyRecord"
                    EventBus.getDefault().post(result)
                }

                override fun onNext(result: ResultInfo<StudyRecordBean>) {
                    result.eventType = "saveOrUpdateStudyRecord"
                    result.msg = flag
                    EventBus.getDefault().post(result)
                }
            })
    }

    fun updateTownInfo(vo: TownshipVo) {

        RxRetrofit.init(ServerConfig.SERVER_URL, ServerConfig.getHeader())
            .create(Api::class.java)
            .updateTownInfo(vo)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Subscriber<ResultInfo<String>>() {

                override fun onCompleted() {}

                override fun onError(e: Throwable) {
                    val result = ResultInfo<String>(ResultInfo.ERROR, ResultInfo.getErrorMsg(e.message))
                    result.eventType = "updateTownInfo"
                    EventBus.getDefault().post(result)
                }

                override fun onNext(result: ResultInfo<String>) {
                    result.eventType = "updateTownInfo"
                    EventBus.getDefault().post(result)
                }
            })
    }
}
